package com.jymj.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jymj.common.validator.ValidatorUtils;
import com.jymj.common.validator.group.AddGroup;
import com.jymj.entity.*;
import com.jymj.entity.dto.*;
import com.jymj.entity.fhtnty.EnviorFileFhEntity;
import com.jymj.entity.fhtnty.HomeEntity;
import com.jymj.entity.fhtnty.ScoreFhEntity;
import com.jymj.entity.landmanage.*;
import com.jymj.entity.model.PointAndTypeEntity;
import com.jymj.entity.model.RjhjhpEntity;
import com.jymj.entity.vo.*;
import com.jymj.service.CJService;
import com.jymj.service.EnviorFileService;
import com.jymj.service.EnviorSupvsService;
import com.jymj.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 环保监察
 */
@RestController
@RequestMapping("EnviorSupvs")
public class EnviorSupvsController extends AbstractController {
    @Autowired
    private EnviorSupvsService enviorSupvsService;
    @Autowired
    private EnviorFileService enviorFileService;
    @Autowired
    private CJService cjService;


    /*
     * 查询 limit page point qutype 1待处理 2整改中 3验收完成
     * */
    @PostMapping(value = "/queryList")
    public R queryList(@RequestBody EnviorSupvsListDto enviorSupvsListDto) {
        if (enviorSupvsListDto.getCode() != null && enviorSupvsListDto.getCode().equals("110112")){
            enviorSupvsListDto.setCode("");
        }
        enviorSupvsListDto.setSysUser(ShiroUtils.getUserEntity());
        PageHelper.startPage(enviorSupvsListDto.getPage(),enviorSupvsListDto.getLimit());
        List<PjEnviorSupvsEntity> enviorSupvsEntities = enviorSupvsService.queryList(enviorSupvsListDto);
        PageInfo<PjEnviorSupvsEntity> pjEnviorSupvsEntityPageInfo = new PageInfo<>(enviorSupvsEntities);
        return R.ok().put("data", pjEnviorSupvsEntityPageInfo);
    }

    /*
     * 按村 查询
     * */
    @PostMapping("/queryByCun")
    public R queryByCun(@RequestBody CunZhenDto cunZhenDto) {

        SysUserEntity userEntity = ShiroUtils.getUserEntity();
        if (userEntity.getType() == 4) {
            return null;
        }
        cunZhenDto.setSysUser(userEntity);
        List<KeyValueEntity> keyValueEntities = enviorSupvsService.queryByCun(cunZhenDto);
        return R.ok().put("data", keyValueEntities);
    }

    @PostMapping("/queryByZhen")
    public R queryByZhen(@RequestBody CunZhenDto cunZhenDto) {
        SysUserEntity userEntity = ShiroUtils.getUserEntity();
        if (userEntity.getType() == 4) {
            return null;
        }
        cunZhenDto.setSysUser(userEntity);
        List<KeyValueEntity> keyValueEntities = enviorSupvsService.queryByZhen(cunZhenDto);
        return R.ok().put("data", keyValueEntities);
    }

    /**
     * 大集统计
     * @param cunZhenDto
     * @return
     */
    @PostMapping("/queryByDj")
    public R queryByDj(@RequestBody CunZhenDto cunZhenDto) {
        List<KeyValueEntity> keyValueEntities = enviorSupvsService.queryByDj(cunZhenDto);
        return R.ok().put("data", keyValueEntities);
    }

    /*
     * 查询村镇各个状态数量   参数code
     * */
    @RequestMapping("/countByCode")
    public R countByCode(@RequestBody EnviorSupvsListDto enviorSupvsDto) {
        KeyValueEntity keyValueEntity = enviorSupvsService.countByCode(enviorSupvsDto);
        return R.ok().put("data", keyValueEntity);
    }

    /**
     * 点查 环保监察
     */
    @RequestMapping("/queryBypoint")
    public R queryBypoint(@RequestBody EnviorSupvsDto enviorSupvsDto) {
        String point = enviorSupvsDto.getPoint();
        PjEnviorSupvsEntity pjEnviorSupvsEntity = enviorSupvsService.queryBypoint(point);
        return R.ok().put("data", pjEnviorSupvsEntity);
    }

    /**
     * 环保监察汇总--- 按时间一个月，三个月，半年，各项目 有多少条
     * 各状态有多少条
     */
//    @RequestMapping(value = "/querySummery", produces = "text/html;charset=UTF-8")
//    public R querySummery() {
//        Map map = new HashMap();
//        List<KeyValueEntity> qutypeList = enviorSupvsService.queryListByqutype();
//        map.put("qutypeList", qutypeList);
//        //一个月内
//        List<KeyValueEntity> oneMonthList = enviorSupvsService.oneMonthList();
//        map.put("oneMonthList", oneMonthList);
//        //三个月内
//        List<KeyValueEntity> threeMonthList = enviorSupvsService.threeMonthList();
//        map.put("threeMonthList", threeMonthList);
//        //半年内
//        List<KeyValueEntity> sixMonthList = enviorSupvsService.sixMonthList();
//        map.put("sixMonthList", sixMonthList);
//        return R.ok().put("data", map);
//    }

    /*
     * 查询村的分数  平均分  上个月的初始分
     * */
    @RequestMapping(value = "/queryScore")
    public R queryScore(String code) {
        ScoreFhEntity scoreFhEntity = enviorSupvsService.queryScore(code);
        return R.ok().put("data", scoreFhEntity);
    }

    /**
     * 点查 公厕 问题信息
     *
     * @param point
     * @return
     */
    @RequestMapping("/queryByPoints")
    public R queryByPoints(String point) {
        PointRecordEntity pointRecordEntity = enviorSupvsService.queryByPoint(point);
        WtlrBean wtlrBean = new WtlrBean();
        wtlrBean.setPointRecordEntity(pointRecordEntity);
        List<PjEnviorSupvsEntity> pjEnviorSupvsEntities = new ArrayList<>();
        if (pointRecordEntity != null) {
            pjEnviorSupvsEntities = enviorSupvsService.queryById(pointRecordEntity.getId());
        } else {
            pjEnviorSupvsEntities = enviorSupvsService.queryByXzq(point);
        }
        wtlrBean.setPjEnviorSupvsEntities(pjEnviorSupvsEntities);
        RjhjhpEntity rjhjhpEntity = cjService.queryCzfw(point);
        Integer i = null;
        if (rjhjhpEntity != null) {
            i = 1;
        } else {
            i = 2;
        }
        wtlrBean.setCzfw(i);
        return R.ok().put("data", wtlrBean);
    }

    /*
     * 查询各个状态的数量图表
     * */
    @RequestMapping("/queryType")
    public R queryType(@RequestBody Map<String, Object> params) {
        List<KeyValueEntity> keyValueEntities = enviorSupvsService.queryType(params);
        return R.ok().put("data", keyValueEntities);
    }

    /*
     * 查询是否存在该村
     * */
    @RequestMapping("/queryCun")
    public R queryCun(String name) {
        List<CjEntity> cjEntityList = null;
        cjEntityList = cjService.queryByName(name, 1);
        if (cjEntityList != null || cjEntityList.size() > 0) {
            cjEntityList = cjService.queryByName(name, 2);
        }
        return R.ok().put("date", cjEntityList);
    }

    @RequestMapping(value = "/save")
    public R save(@RequestBody PjEnviorSupvsEntity pjEnviorSupvsEntity) {
        pjEnviorSupvsEntity.setFavorite(0);
        pjEnviorSupvsEntity.setCreateTime(new Date());
        if (pjEnviorSupvsEntity.getZjwj() == null) {
            pjEnviorSupvsEntity.setZjwj(0);
        }
        if (pjEnviorSupvsEntity.getCode() == null || "".equals(pjEnviorSupvsEntity.getCode())){
            throw new RRException("村名不能为空");
        }
        ValidatorUtils.validateEntity(pjEnviorSupvsEntity, AddGroup.class);
        //先通过点查询是否在权限范围内
        if (pjEnviorSupvsEntity.getLocation() != null) {
            String point = pjEnviorSupvsEntity.getLocation();
            /*boolean istrue = enviorSupvsService.queryIstrue(point);
            if(!istrue){
                return R.error("所在区域超出范围！");
            }*/
            String objStr = point.substring(point.indexOf("(") + 1, point.indexOf(")"));
            ArrayList list = new ArrayList(Arrays.asList(objStr.split(" ")));
            pjEnviorSupvsEntity.setX(new BigDecimal(list.get(0).toString()));
            pjEnviorSupvsEntity.setY(new BigDecimal(list.get(1).toString()));
        }
        if (pjEnviorSupvsEntity.getHjzzsj() != null) {
            if (pjEnviorSupvsEntity.getHjzzsj() == 1014) {
                //判断查询 每月一条的环境评价是否存在
                PjEnviorSupvsEntity enviorSupvsEntity = enviorSupvsService.queryHjpj(pjEnviorSupvsEntity.getLocation());
                if (enviorSupvsEntity != null) {
                    return R.error("环境评价已存在");
                }
            }
        }
        //
        SysUserEntity userEntity = ShiroUtils.getUserEntity();
        if (userEntity.getType() != 1 && userEntity.getType() != 4) {
            return R.error("无权限");
        }

        pjEnviorSupvsEntity.setEnpsn(Integer.parseInt(getUserId().toString()));
        pjEnviorSupvsEntity.setJltime(new Date());
        Integer msid = -1;
        if (pjEnviorSupvsEntity.getHjzzfls() != null || pjEnviorSupvsEntity.getHjzzfls().length > 0) {
            Integer[] hjzzfls = pjEnviorSupvsEntity.getHjzzfls();
            List<PjEnviorSupvsEntity> supvsEntitylist = new ArrayList<>();
            for (Integer hjzzfl : hjzzfls) {
                pjEnviorSupvsEntity.setHjzzsj(hjzzfl);
                enviorSupvsService.save(pjEnviorSupvsEntity);
                supvsEntitylist.add(pjEnviorSupvsEntity);
            }

            msid = supvsEntitylist.get(0).getId();
        } else {
            enviorSupvsService.save(pjEnviorSupvsEntity);

            msid = pjEnviorSupvsEntity.getId();
        }
        if (pjEnviorSupvsEntity.getFileIds() != null && pjEnviorSupvsEntity.getFileIds().length > 0) {
            Integer[] fileIds = pjEnviorSupvsEntity.getFileIds();
            enviorFileService.updateMsid(msid, fileIds);
        }
        return R.ok().put("data", "添加成功");
    }

    /**
     * 状态回滚
     * id ：integer 需修改项id
     * qutype ：integer 驳回至状态
     * comment ：String 驳回备注
     * qutype传3判断原值是否为4，qutype 4改3
     * qutype传1判断原值是否为3，qutype 3改1
     * qutype传0判断原值是否为1，qutype 1改0 ，comment ：String 驳回备注
     * @param id
     * @param qutype
     * @return
     */
    @PostMapping("/fallBackQutype")
    public R fallBackQutype(Integer id, Integer qutype, String comment) {
        enviorSupvsService.fallBackQutype(id, qutype, comment);
        return R.ok("修改成功");
    }


    @RequestMapping(value = "/update")
    public R update(@RequestBody PjEnviorSupvsEntity pjEnviorSupvsEntity) {
        enviorSupvsService.rejected(pjEnviorSupvsEntity);
        return R.ok("完成驳回");
    }

    @RequestMapping("/info")
    public R info(Integer id) {
        PjEnviorSupvsEntity enviorSupvsEntity = enviorSupvsService.queryInfo(id);
        List<PjEnviorRejectedEntity> enviorRejectedEntities = enviorSupvsService.queryRej(id);
        PointRecordEntity pointRecordEntity = new PointRecordEntity();
        if (enviorSupvsEntity != null) {
            pointRecordEntity = enviorSupvsService.queryPointInfo(enviorSupvsEntity.getGddwid());
        }
        RjhjInfoBean rjhjInfoBean = new RjhjInfoBean();
        rjhjInfoBean.setEnviorSupvsEntity(enviorSupvsEntity);
        rjhjInfoBean.setEnviorRejectedEntities(enviorRejectedEntities);
        rjhjInfoBean.setPointRecordEntity(pointRecordEntity);
        return R.ok().put("data", rjhjInfoBean);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @RequestMapping(value = "/delete")
    public R delete(Integer id, HttpServletRequest request) {
        if (id==null){
            throw new RRException("无参数,查询失败");
        }
        String savePath = request.getSession().getServletContext().getRealPath("/");
        List<PjEnviorFileEntity> pjEnviorFileEntities = enviorFileService.queryObjectBymsId(id);
        for (PjEnviorFileEntity aa : pjEnviorFileEntities) {
            File file = new File(savePath + aa.getPath());
            if (file.exists()) {
                file.delete();
            }
        }
        List<PjEnviorRejectedEntity> enviorRejectedEntities = enviorSupvsService.queryRej(id);
        for (PjEnviorRejectedEntity enviorRejectedEntity : enviorRejectedEntities) {
            for (PjEnviorRejectedFile enviorRejectedFile : enviorRejectedEntity.getEnviorRejectedFiles()) {
                File file = new File(savePath + enviorRejectedFile.getPath());
                if (file.exists()) {
                    file.delete();
                }
            }
        }
        enviorSupvsService.delete(id);
        return R.ok("删除成功");
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @RequestMapping(value = "/deleteBatch")
    public R deleteBatch(@RequestBody Long... ids) throws FileNotFoundException {
        if (ids == null || ids.length==0){
            throw new RRException("参数不能为空");
        }
        File genPath = new File(ResourceUtils.getURL("jar:").getPath());
        File savePath1 = new File(genPath.getAbsolutePath().replace("jar:", "fileupload"));
        List<PjEnviorFileEntity> pjEnviorFileEntities = enviorFileService.queryListByMsids(ids);
        for (PjEnviorFileEntity aa : pjEnviorFileEntities) {
            File file = new File(savePath1 + File.separator + aa.getPath());
            file.delete();
        }
        enviorSupvsService.deleteBatch(ids);
        return R.ok("删除成功");
    }

    /*
     * 定点列表
     * */
    @RequestMapping("/queryPointList")
    public R queryPointList(@RequestBody PointPageDto pointPageDto) {
        PageHelper.startPage(pointPageDto.getPage(), pointPageDto.getLimit());
        List<PointRecordEntity> pointRecordEntities = enviorSupvsService.queryPointList(pointPageDto);
        PageInfo<PointRecordEntity> pointRecordEntityPageInfo = new PageInfo(pointRecordEntities);
        return R.ok().put("data", pointRecordEntityPageInfo);
    }

    /*
     * 添加定点位置
     * */
    @RequestMapping("/savePoint")
    public R savePoint(@RequestBody PointRecordEntity pointRecordEntity) {
        enviorSupvsService.savePoint(pointRecordEntity);
        return R.ok("添加成功");
    }

    /*
     * 添加定点位置
     * */
    @RequestMapping("/updatePoint")
    public R updatePoint(@RequestBody PointRecordEntity pointRecordEntity) {
        enviorSupvsService.updatePoint(pointRecordEntity);
        return R.ok().put("date", pointRecordEntity);
    }

    /*
     * 删除定点位置
     * */
    @RequestMapping("/deletePoint")
    public R deletePoint(@RequestBody Integer[] ids) {
        if (ids == null && ids.length == 0) {
            return R.ok("无参数");
        }
        List<PjEnviorSupvsEntity> pjEnviorSupvsEntities = enviorSupvsService.queryListByIds(ids);
        if (pjEnviorSupvsEntities != null && pjEnviorSupvsEntities.size() > 0) {
            return R.error("公厕未处理,无法删除");
        }
        enviorSupvsService.deletePoint(ids);
        return R.ok();
    }

    /*
     * 人居环境首页
     * */
    @RequestMapping("/queryHome")
    public R queryHome(@RequestBody ReportDto reportDto) {
        FirstHomeBean firstHomeBean = new FirstHomeBean();

        //按镇查询问题数
        List<HomeEntity> homeEntities = enviorSupvsService.queryHomeZhen(reportDto);
        firstHomeBean.setHomeEntities(homeEntities);
        //查询问题数最多镇
        if(reportDto.getType() ==null)reportDto.setType(1);
        RjhjReport rjhjReport = enviorSupvsService.rjhjReport(reportDto);
        firstHomeBean.setRjhjReport(rjhjReport);
        //按时间 查询区的问题数
        HomeEntity homeEntity = enviorSupvsService.queryHome(reportDto);
        firstHomeBean.setHomeEntity(homeEntity);
        return R.ok().put("data", firstHomeBean);
    }

    /**
     * 查询区镇村 环境占比表
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping("/queryFlZb")
    public R queryFlZb(@RequestBody ReportDto reportDto) {
        Integer type = reportDto.getType() == null ? 2 : reportDto.getType();
        reportDto.setType(type);
        RjhjReport rjhjReport = enviorSupvsService.rjhjReport(reportDto);
        return R.ok().put("data", rjhjReport);
    }

    /*
     * 人居环境 日志  参数 时间 yyyy-mm-dd
     * */
    @RequestMapping("/rjhjJournal")
    public R rjhjJournal(String date) {
        List<JournalEntity> journalEntities = enviorSupvsService.queryJournal(date, 1);
        return R.ok().put("data", journalEntities);
    }

    /*
     * 人居环境 月报  参数 时间 yyyy-mm
     * */
    @RequestMapping("/rjhjReport")
    public R rjhjReport(String date) {
        //查询全部问题点位
        RjhjReport rjhjReport = enviorSupvsService.rjhjReport(new ReportDto().setDate(date).setType(1));
        //查询未处理问题点位
        RjhjReport rjhjReport1 = enviorSupvsService.rjhjReport(new ReportDto().setDate(date).setType(2));
        //查询区平均分和占比
        ScoreReport scoreReport = enviorSupvsService.scoreReport(date);
        //查询不合格村庄数
        List<ScoreMonEntity> scoreMonEntities = enviorSupvsService.bhgcz(date, 1);
        //镇排名
        List<ScoreMonEntity> scoreMonEntityList = enviorSupvsService.bhgcz(date, 2);
        scoreMonEntityList.sort(Comparator.comparing(ScoreMonEntity::getAverage).reversed());
        //查询典型问题的村庄
        List<JournalEntity> journalEntities = enviorSupvsService.queryDxwt(date, 1);
        MonthlyEntity1 monthlyEntity1 = new MonthlyEntity1();
        monthlyEntity1.setRjhjReport(rjhjReport);
        monthlyEntity1.setRjhjReport1(rjhjReport1);
        monthlyEntity1.setScoreReport(scoreReport);
        monthlyEntity1.setScoreMonEntities(scoreMonEntities);
        monthlyEntity1.setScoreMonEntityList(scoreMonEntityList);
        monthlyEntity1.setJournalEntities(journalEntities);
        return R.ok().put("data", monthlyEntity1);
    }

    /*
     * 查询日志
     * */
    @RequestMapping("/enviorLog")
    public R enviorLog(String date) {
        List<PjEnviorSupvsLog> pjEnviorSupvsLogList = new ArrayList<>();
        List<PjEnviorSupvsLog> pjEnviorSupvsLog = enviorSupvsService.enviorLog(date);
        for (PjEnviorSupvsLog pjEnviorSupvsLog1 : pjEnviorSupvsLog) {
            PjEnviorSupvsLog enviorSupvsLog = new PjEnviorSupvsLog();
            enviorSupvsLog.setUptime(pjEnviorSupvsLog1.getUptime());
            List<JournalEntity> journalEntities =
                    JsonXMLUtils.getListByJSONArray(JournalEntity.class, pjEnviorSupvsLog1.getJsontext());
            enviorSupvsLog.setJournalEntities(journalEntities);
            pjEnviorSupvsLogList.add(enviorSupvsLog);
        }
        pjEnviorSupvsLogList.sort(Comparator.comparing(PjEnviorSupvsLog::getUptime).reversed());
        return R.ok().put("data", pjEnviorSupvsLogList);
    }


    /**
     * 根据xy坐标查询问题数量与具体问题点位
     *
     * @param pointAndTypeEntity
     * @return
     */
    @PostMapping("/getEnviorsByxy")
    public R getEnviorsByxy(@RequestBody PointAndTypeEntity pointAndTypeEntity) {
        List<EnviorFileFhEntity> enviorFileFhEntities = enviorSupvsService.getEnviorsByxy(pointAndTypeEntity);
        return R.ok().put("data", enviorFileFhEntities);
    }

    @PostMapping("/updateQutype")
    public R updateQutype(@RequestBody PjEnviorSupvsEntity pjEnviorSupvsEntity){
        if (ShiroUtils.getUserEntity().getUserId()!=1){
            throw new RRException("无权限修改");
        }
        enviorSupvsService.updateQutype(pjEnviorSupvsEntity);
        return R.ok("修改成功");
    }

    /**
     * 查询操作日志
     * @param enviorSupvsLogEntity
     * @return
     */
    @PostMapping("/getEnviorLog")
    public R getEnviorLog(@RequestBody EnviorSupvsLogEntity enviorSupvsLogEntity){
        PageHelper.startPage(enviorSupvsLogEntity.getPage(),enviorSupvsLogEntity.getLimit());
        List<EnviorSupvsLogEntity> enviorSupvsLogEntities = enviorSupvsService.getEnviorLog(enviorSupvsLogEntity);
        PageInfo<EnviorSupvsLogEntity> enviorSupvsLogEntityPageInfo = new PageInfo<>(enviorSupvsLogEntities);
        return R.ok().put("data",enviorSupvsLogEntityPageInfo);
    }

    /**
     * 驾驶舱统计5中问题类型
     * @return
     */

    @PostMapping("/getQuestionCount")
    public R getQuestionCount(){
        QuestionCount questionCount = enviorSupvsService.getQuestionCount();
        return R.ok().put("data", questionCount);
    }

    /**
     * 修改收藏标记
     * @param pjEnviorSupvsEntity
     * @return
     */
    @PostMapping("/updateFav")
    public R updateFav(@RequestBody PjEnviorSupvsEntity pjEnviorSupvsEntity){
        enviorSupvsService.updateBh(pjEnviorSupvsEntity);
        return R.ok("修改成功");
    }


}
